package cn.com.cnxfs.relaxchat.service.impl;

import cn.com.cnxfs.relaxchat.service.IPhotoService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;

@Service
public class PhotoService implements IPhotoService {
    @Override
    public String upload(MultipartFile file) {
        if(file.isEmpty()){
            return "400";
        }
        String OriginalFilename = file.getOriginalFilename();
        String fileName = System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
        String filePath = System.getProperty("user.dir") + "\\upload\\photo\\";
        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists()){ //检查目录是否存在
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); //上传文件
        }catch (Exception e){
            e.printStackTrace();
            return "500";
        }
        return fileName;
    }

    @Override
    public String del(String name) {
        try {
            File file = new File(System.getProperty("user.dir") + "\\upload\\photo\\" + name);
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
